package cn.lanqiao.dao.impl;

import cn.lanqiao.dao.AccountDao;
import cn.lanqiao.jdbc.pojo.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository("dao")
public class AccountDaoImpl implements AccountDao {
    @Autowired
    private JdbcTemplate template;

    @Override
    public void insert(Account account) {
        String sql = "insert into account(accname,balance) values(?,?)";
        template.update(sql,account.getAccname(),account.getBalance());
    }

    @Override
    public void update(Account account) {
        String sql = "update account set balance=? where id=?";
        template.update(sql,account.getBalance(),account.getId());
    }

    @Override
    public void delete(int id) {
        String sql = "delete from account where id= ?";
        template.update(sql,id);
    }

    @Override
    public Account selectOne(int id) {
        String sql = "select * from account where id = ?";
        return template.queryForObject(sql, new RowMapper<Account>() {
            @Override
            public Account mapRow(ResultSet resultSet, int i) throws SQLException {
                Account acc = new Account();
                acc.setId(resultSet.getInt("id"));
                acc.setAccname(resultSet.getString("accname"));
                acc.setBalance(resultSet.getInt("balance"));
                return acc;
            }
        }, id);
    }

    @Override
    public List<Account> selectAll() {
        String sql = "select * from account";
        return template.query(sql, new RowMapper<Account>() {
            @Override
            public Account mapRow(ResultSet resultSet, int i) throws SQLException {
                Account acc = new Account();
                acc.setId(resultSet.getInt("id"));
                acc.setAccname(resultSet.getString("accname"));
                acc.setBalance(resultSet.getInt("balance"));
                return acc;
            }
        });
    }

    @Override
    public Integer count(){
        String sql = "select count(*) from account";
        return template.queryForObject(sql,Integer.class);
    }

    @Override
    public void updateBalance(String accname, Integer money) {
        String sql = "update account set balance=balance+? where accname=?";
        template.update(sql,money,accname);
    }
}
